from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, DestroyModelMixin, ListModelMixin, RetrieveModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.permissions import IsAuthenticated

from community.models import Article, Comment
from community.serializers import ArticleSerializer, CommentSerializer, CommentHandleSerializer
from utils.permissions import create_auto_user, update_auto_user, destroy_auto_user


class ArticlePaginationNumber(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'  # 每页显示多少条数据
    # page_query_param = 'page'
    max_page_size = 100


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]

    pagination_class = ArticlePaginationNumber

    @create_auto_user
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @update_auto_user(Article)
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @destroy_auto_user(Article)
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    # 对于浏览量增加的功能编写
    def retrieve(self, request, *args, **kwargs):
        Article.objects.filter(id=kwargs['pk']).update(page_view=F('page_view')+1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=['get'], detail=True)
    def comment(self, request, pk):
        comment = Comment.objects.filter(level=1, article=pk)
        serializer = CommentHandleSerializer(comment, many=True)
        return Response(serializer.data)


class CommentViewSet(GenericViewSet, CreateModelMixin, DestroyModelMixin, ListModelMixin, RetrieveModelMixin):
    queryset = Comment.objects.filter(level=1)
    serializer_class = CommentHandleSerializer
    permission_classes = [IsAuthenticated]

    @create_auto_user
    def create(self, request, *args, **kwargs):
        return CreateModelMixin.create(self, request, *args, **kwargs)

    @destroy_auto_user(Comment)
    def destroy(self, request, *args, **kwargs):
        return DestroyModelMixin.destroy(self, request, *args, **kwargs)